package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.yblog.common.exception.Asserts;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.crud.entity.Post;
import com.yuan.yblog.crud.entity.User;
import com.yuan.yblog.crud.entity.UserCollection;
import com.yuan.yblog.crud.service.IPostService;
import com.yuan.yblog.crud.service.IUserCollectionService;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.portal.dao.mapper.UserCollectionDao;
import com.yuan.yblog.portal.pojo.VO.UserCollectionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 13527
 * @description 针对表【user_collection】的数据库操作Service实现
 * @createDate 2023-12-03 14:18:01
 */
@Service
public class UserCollectionService {

    @Autowired
    UserCollectionDao userCollectionDao;

    @Autowired
    IUserService iUserService;

    @Autowired
    IUserCollectionService iUserCollectionService;

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    IPostService iPostService;

    @Autowired
    EntityCacheService entityCacheService;

    /**
     * 分页查询用户收藏文章
     */
    public IPage<UserCollectionVO> list(Long pageNumber, Long pageSize, String sort, Boolean isDesc) {
        User user = authenticationService.getLoginUser();
        List<UserCollection> list = userCollectionDao.listAll(user.getId(), (pageNumber-1)*pageSize, pageSize, sort, isDesc);
        long total = iUserCollectionService.count(new QueryWrapper<UserCollection>().eq("user_id",user.getId()));
        // 转化
        List<UserCollectionVO> data = new ArrayList<>();
        for (UserCollection userCollection : list) {
            Post post = iPostService.selectByIdAndBuildCache(userCollection.getPostId());
            User postAuthor = iUserService.selectByIdAndBuildCache(userCollection.getPostUserId());
            data.add(UserCollectionVO.getUserCollectionVO(userCollection, post, postAuthor));
        }
        //封装返回
        IPage<UserCollectionVO> result = new Page<>(pageNumber,pageSize,total);
        result.setRecords(data);
        return result;
    }

    /**
     * 用户点击收藏
     * @param userCollectionVO 收藏信息
     */
    public Long insert(UserCollectionVO userCollectionVO) {
        if(isCollected(userCollectionVO.getPostId())){
            // 用户已收藏
            return null;
        }
        User loginUser = authenticationService.getLoginUser();
        if(!userCollectionVO.getUserId().equals(loginUser.getId())
                ||userCollectionVO.getPostId()==null
                ||userCollectionVO.getPostUserId()==null){
            Asserts.fail("非法操作");
        }
        UserCollection insertEntity = userCollectionVO.toInsertEntity();
        boolean success = iUserCollectionService.insert(insertEntity);
        if (success) {
            // 更新用户收藏数
            User user = iUserService.selectByIdAndBuildCache(loginUser.getId());
            user.setCollectCount(user.getCollectCount() + 1);
            iUserService.updateAndDeleteCache(user);

            // 插入成功
            return insertEntity.getId();
        }
        return null;
    }

    /**
     * 删除当前用户【指定文章id】的收藏
     * @param postIds 文章id
     * @return 生效数目
     */
    public int delete(List<Long> postIds) {
        long userId = authenticationService.getLoginUser().getId();
        int count = 0;
        List<UserCollection> list = iUserCollectionService.getBaseMapper().selectList(new QueryWrapper<UserCollection>()
                .eq("user_id",userId)
                .in("post_id",postIds));
        for (UserCollection userCollection : list) {
            count += iUserCollectionService.physicalDeleteAndDeleteCache(userCollection.getId()) ? 1 : 0;
        }
        // 更新用户收藏数
        User user = iUserService.selectByIdAndBuildCache(userId);
        user.setCollectCount(user.getCollectCount() - count);
        iUserService.updateAndDeleteCache(user);

        return count;
    }

    /**
     * 判断当前用户是否已收藏该文章
     * @param postId 文章id
     */
    public Boolean isCollected(Long postId) {
        User user = authenticationService.getLoginUser();
        return iUserCollectionService.count(new QueryWrapper<UserCollection>()
                .eq("user_id",user.getId())
                .eq("post_id",postId))
                >0;
    }
}




